<?php


namespace common\components\form\field;

use Yii;
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use common\components\form\Form;
use common\components\form\Field;

/**
 * description of Datetime
 *
 * @author FireLoong
 */
class Datetime extends Field
{
    public function setup($options = ['autocomplete' => 'off'])
    {
        if ($this->setupParams) {
            $options = $this->setupParams[0] ? ArrayHelper::merge($this->setupParams[0], $options) : $options;
        }

        $options = array_merge($this->inputOptions, $options);

        if ($this->form->validationStateOn === Form::VALIDATION_STATE_ON_INPUT) {
            $this->addErrorClassIfNeeded($options);
        }

        $this->addAriaAttributes($options);
        $this->adjustLabelFor($options);

        $id = $this->getInputId();
        $name = isset($options['name']) ? $options['name'] : Html::getInputName($this->model, $this->attribute);
        $value = isset($options['value']) ? $options['value'] : Html::getAttributeValue($this->model, $this->attribute);
        $options['id'] = 'as-' . $id;
        $input = Html::activeTextInput($this->model, $this->attribute, $options);
        $input .= Html::hiddenInput($name, $value, ['id' => $id]);
        $this->parts['{input}'] = $input;

        $this->form->assets['datetime'] = [
            'css' => 'https://cdn.jsdelivr.net/npm/daterangepicker@3.0.5/daterangepicker.min.css',
            'js' => [
                'https://cdn.jsdelivr.net/npm/moment@2.24.0/moment.min.js',
                'https://cdn.jsdelivr.net/npm/moment@2.24.0/locale/' . (strtolower(Yii::$app->language)) . '.min.js',
                'https://cdn.jsdelivr.net/npm/daterangepicker@3.0.5/daterangepicker.min.js'
            ],
            'bundles' => ['yii\bootstrap\BootstrapThemeAsset', 'yii\bootstrap\BootstrapPluginAsset']
        ];

        $this->form->view->registerJs('var format = \'YYYY-MM-DD HH:mm:ss\';');
        $uniqueId = \yii\helpers\Inflector::variablize($id);
        if ($value) {
            $this->form->view->registerJs('$(\'#as-' . $id . '\').val(moment(\'' . $value . '\', \'X\').format(format));');
            $this->form->view->registerJs('var ' . $uniqueId . 'StartDate = moment(\'' . $value . '\', \'X\').format(format);');
        } else {
            $this->form->view->registerJs('var ' . $uniqueId . 'StartDate = moment().format(format);');
        }
        $cancelLabel = Yii::t('common', 'CANCEL');
        $applyLabel = Yii::t('common', 'APPLY');
        $drops = $options['drops'] ?? 'down';
        $js = <<<JS
$('#as-$id').daterangepicker({
    autoUpdateInput: false,
    singleDatePicker: true,
    showDropdowns: true,
    timePicker: true,
    timePicker24Hour: true,
    timePickerSeconds: true,
    startDate: {$uniqueId}StartDate,
    drops: '$drops',
    locale: {
        format: format,
        cancelLabel: '$cancelLabel',
        applyLabel: '$applyLabel'
    }
});
$('#as-$id').on('apply.daterangepicker', function(ev, picker) {
  $(this).val(picker.startDate.format(format));
  $('#$id').val(picker.startDate.format('X')).focus().blur();
});
$('#as-$id').on('cancel.daterangepicker', function(ev, picker) {
  $(this).val('');
  $('#$id').val('').focus().blur();
});
$('body').on('change', '#as-$id', function() {
    if($(this).val() === ''){
        $('#$id').val('').focus().blur();
    }else{
        const timestamp = moment($(this).val()).format('X');
        $('#$id').val(timestamp).focus().blur();
    }
});
JS;

        $this->form->view->registerJs($js);
        $css = <<<CSS
.daterangepicker select.monthselect{float:left;}
.daterangepicker select.yearselect{float:right;}
.daterangepicker select{
    border: 1px solid #ccc;
    border-radius: 4px;
    background-color: #f0f0f0;
    height: 25px;
    line-height: 25px;
}
.daterangepicker .calendar-table th, .daterangepicker .calendar-table td{padding: 0;}
CSS;

        $this->form->view->registerCss($css);

        return $this;
    }
}
